<template>
  <div class="app-container">
    <!-- 顶部操作栏 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.kw"
        placeholder="搜索网站名称、域名..."
        style="width: 300px;"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
      />
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        type="success"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        新建网站
      </el-button>
      <el-button
        v-if="canSyncFromProduction"
        class="filter-item"
        type="warning"
        icon="el-icon-refresh"
        @click="handleSyncFromProduction"
      >
        同步生产环境
      </el-button>
    </div>

    <!-- 网站列表 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" width="80" align="center">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="网站名称" min-width="150">
        <template slot-scope="{row}">
          <el-link type="primary" @click="handleView(row)">
            <strong>{{ row.name }}</strong>
          </el-link>
          <div style="font-size: 12px; color: #999;">{{ row.domain }}</div>
        </template>
      </el-table-column>

      <el-table-column label="框架" width="120" align="center">
        <template slot-scope="{row}">
          <el-tag :type="getFrameworkType(row.framework)">
            {{ row.framework }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="颜色配置" width="180" align="center">
        <template slot-scope="{row}">
          <div style="display: flex; justify-content: center; gap: 5px;">
            <div
              :style="{ backgroundColor: row.primary_color, width: '50px', height: '24px', borderRadius: '3px', border: '1px solid #ddd' }"
              :title="'主色: ' + row.primary_color"
            />
            <div
              :style="{ backgroundColor: row.secondary_color, width: '50px', height: '24px', borderRadius: '3px', border: '1px solid #ddd' }"
              :title="'辅色: ' + row.secondary_color"
            />
            <div
              :style="{ backgroundColor: row.accent_color || '#ffc107', width: '50px', height: '24px', borderRadius: '3px', border: '1px solid #ddd' }"
              :title="'强调色: ' + (row.accent_color || '#ffc107')"
            />
          </div>
        </template>
      </el-table-column>

      <el-table-column label="构建状态" width="120" align="center">
        <template slot-scope="{row}">
          <el-tag :type="getBuildStatusType(row.build_status)">
            {{ getBuildStatusText(row.build_status) }}
          </el-tag>
          <div v-if="row.build_version" style="font-size: 12px; color: #999;">
            v{{ row.build_version }}
          </div>
        </template>
      </el-table-column>

      <el-table-column label="页面数" width="100" align="center">
        <template slot-scope="{row}">
          <span>{{ row.page_count || 0 }}</span>
        </template>
      </el-table-column>

      <el-table-column label="最后构建" width="160" align="center">
        <template slot-scope="{row}">
          <span v-if="row.last_build_at">{{ row.last_build_at | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
          <span v-else style="color: #999;">未构建</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="360" align="center" fixed="right">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" icon="el-icon-document" @click="handleManagePages(row)">
            页面管理
          </el-button>
          <el-button type="warning" size="mini" icon="el-icon-folder-add" @click="handleBuild(row)">
            创建静态目录
          </el-button>
          <el-dropdown
            trigger="click"
            style="margin-left: 10px;"
            @command="(cmd) => handleDeployCommand(cmd, row)"
          >
            <el-button
              size="mini"
              style="background-color: #1EB7E6; border-color: #1EB7E6; color: white;"
            >
              部署<i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="local" icon="el-icon-document-copy">批量创建MD</el-dropdown-item>
              <el-dropdown-item command="cloudflare" icon="el-icon-cloudy">Cloudflare Pages</el-dropdown-item>
              <el-dropdown-item command="github" icon="el-icon-upload2">推送到 GitHub</el-dropdown-item>
              <el-dropdown-item command="github-pull" icon="el-icon-download" divided>从 GitHub 同步代码</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-dropdown
            trigger="click"
            style="margin-left: 10px;"
            @command="(cmd) => handleMoreCommand(cmd, row)"
          >
            <el-button size="mini" icon="el-icon-more">
              更多<i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-if="row.deploy_status === 'deployed'"
                command="preview"
                icon="el-icon-view"
              >
                预览网站
              </el-dropdown-item>
              <el-dropdown-item command="config" icon="el-icon-setting">
                网站配置
              </el-dropdown-item>
              <el-dropdown-item command="cloud-images" icon="el-icon-picture-outline">
                云端图片
              </el-dropdown-item>
              <el-dropdown-item command="edit" icon="el-icon-edit">
                编辑信息
              </el-dropdown-item>
              <el-dropdown-item command="delete" icon="el-icon-delete" divided>
                删除网站
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-if="total>0"
      background
      class="mt-pagination"
      :current-page="listQuery.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="listQuery.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />

    <!-- Cloudflare 部署对话框 -->
    <el-dialog
      title="部署到 Cloudflare Pages"
      :visible.sync="cloudflareDialogVisible"
      width="700px"
    >
      <div v-loading="loadingConfigs">
        <el-alert
          type="info"
          :closable="false"
          style="margin-bottom: 20px;"
        >
          <div slot="title">
            <strong>部署网站: {{ currentWebsite ? currentWebsite.name : '' }}</strong>
          </div>
          即将部署到 Cloudflare Pages。请选择一个已配置的 Cloudflare 账户。
        </el-alert>

        <el-form label-width="120px">
          <el-form-item label="Cloudflare 配置">
            <el-select
              v-model="selectedConfigId"
              placeholder="请选择 Cloudflare 配置"
              style="width: 100%;"
            >
              <el-option
                v-for="config in cloudflareConfigs"
                :key="config.id"
                :label="`${config.name} (${config.project_name})`"
                :value="config.id"
              >
                <span style="float: left">{{ config.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">
                  {{ config.project_name }}
                </span>
              </el-option>
            </el-select>
            <div style="margin-top: 8px; font-size: 12px; color: #909399;">
              <el-link
                type="primary"
                icon="el-icon-setting"
                @click="goToCloudflareConfig"
              >
                管理 Cloudflare 配置
              </el-link>
            </div>
          </el-form-item>

          <el-form-item v-if="selectedConfigId" label="配置详情">
            <div style="padding: 10px; background: #f5f7fa; border-radius: 4px; font-size: 13px;">
              <div v-for="config in cloudflareConfigs.filter(c => c.id === selectedConfigId)" :key="config.id">
                <p><strong>项目名称:</strong> {{ config.project_name }}</p>
                <p><strong>Account ID:</strong> {{ config.account_id }}</p>
                <p v-if="config.last_used_at"><strong>上次使用:</strong> {{ config.last_used_at }}</p>
              </div>
            </div>
          </el-form-item>
        </el-form>

        <!-- 部署历史 -->
        <div v-if="deploymentHistory.length > 0" style="margin-top: 20px;">
          <el-divider content-position="left">最近部署记录</el-divider>
          <el-table :data="deploymentHistory.slice(0, 3)" size="small" border>
            <el-table-column label="状态" width="80" align="center">
              <template slot-scope="{row}">
                <el-tag :type="getDeployStatusType(row.status)" size="mini">
                  {{ getDeployStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="配置" prop="config_name" show-overflow-tooltip />
            <el-table-column label="文件数" prop="files_count" width="80" align="center" />
            <el-table-column label="页面数" prop="pages_count" width="80" align="center" />
            <el-table-column label="时间" prop="start_at" width="150" />
          </el-table>
          <div style="text-align: center; margin-top: 10px;">
            <el-link type="primary" @click="viewFullHistory">查看完整历史</el-link>
          </div>
        </div>
      </div>

      <div slot="footer">
        <el-button @click="cloudflareDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          icon="el-icon-upload"
          style="background-color: #1EB7E6; border-color: #1EB7E6;"
          :loading="deploying"
          :disabled="!selectedConfigId"
          @click="handleCloudflareDeployConfirm"
        >
          {{ deploying ? '部署中...' : '开始部署' }}
        </el-button>
      </div>
    </el-dialog>

    <!-- GitHub 部署对话框 -->
    <el-dialog
      title="部署到 GitHub"
      :visible.sync="githubDialogVisible"
      width="700px"
    >
      <div v-loading="loadingGithubConfigs">
        <el-alert
          type="info"
          :closable="false"
          style="margin-bottom: 20px;"
        >
          <div slot="title">
            <strong>部署网站: {{ currentWebsite ? currentWebsite.name : '' }}</strong>
          </div>
          将网站推送到 GitHub 仓库，可以在 Cloudflare Pages 中设置 GitHub 同步。
        </el-alert>

        <el-form label-width="120px">
          <el-form-item label="GitHub 配置">
            <el-select
              v-model="selectedGithubConfigId"
              placeholder="请选择 GitHub 配置"
              style="width: 100%;"
            >
              <el-option
                v-for="config in githubConfigs"
                :key="config.id"
                :label="`${config.name} (${config.username})`"
                :value="config.id"
              >
                <span style="float: left">{{ config.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">
                  @{{ config.username }}
                </span>
              </el-option>
            </el-select>
            <div style="margin-top: 8px; font-size: 12px; color: #909399;">
              <el-link
                type="primary"
                icon="el-icon-setting"
                @click="goToGithubConfig"
              >
                管理 GitHub 配置
              </el-link>
            </div>
          </el-form-item>

          <el-form-item v-if="selectedGithubConfigId" label="配置详情">
            <div style="padding: 10px; background: #f5f7fa; border-radius: 4px; font-size: 13px;">
              <div v-for="config in githubConfigs.filter(c => c.id === selectedGithubConfigId)" :key="config.id">
                <p><strong>用户名:</strong> {{ config.username }}</p>
                <p><strong>仓库前缀:</strong> {{ config.repo_prefix || '无' }}</p>
                <p><strong>默认分支:</strong> {{ config.default_branch }}</p>
                <p><strong>仓库类型:</strong> {{ config.private_repo ? '私有' : '公开' }}</p>
                <p v-if="config.last_used_at"><strong>上次使用:</strong> {{ config.last_used_at }}</p>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="提交信息">
            <el-input
              v-model="githubCommitMessage"
              placeholder="Update website content"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-form>

        <!-- 部署历史 -->
        <div v-if="githubDeploymentHistory.length > 0" style="margin-top: 20px;">
          <el-divider content-position="left">最近部署记录</el-divider>
          <el-table :data="githubDeploymentHistory.slice(0, 3)" size="small" border>
            <el-table-column label="状态" width="80" align="center">
              <template slot-scope="{row}">
                <el-tag :type="getGithubDeployStatusType(row.status)" size="mini">
                  {{ getGithubDeployStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="仓库" prop="repo_name" show-overflow-tooltip />
            <el-table-column label="分支" prop="branch" width="80" align="center" />
            <el-table-column label="时间" prop="start_at" width="150" />
          </el-table>
          <div style="text-align: center; margin-top: 10px;">
            <el-link type="primary" @click="viewGithubFullHistory">查看完整历史</el-link>
          </div>
        </div>
      </div>

      <div slot="footer">
        <el-button @click="githubDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          icon="el-icon-upload"
          style="background-color: #1EB7E6; border-color: #1EB7E6;"
          :loading="deployingToGithub"
          :disabled="!selectedGithubConfigId"
          @click="handleGithubDeployConfirm"
        >
          {{ deployingToGithub ? '推送中...' : '推送到 GitHub' }}
        </el-button>
      </div>
    </el-dialog>

    <!-- GitHub 部署历史详情对话框 -->
    <el-dialog
      title="GitHub 部署历史"
      :visible.sync="githubHistoryDialogVisible"
      width="1000px"
    >
      <el-table :data="githubDeploymentHistory" border>
        <el-table-column label="ID" prop="id" width="60" align="center" />
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="{row}">
            <el-tag :type="getGithubDeployStatusType(row.status)">
              {{ getGithubDeployStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="仓库名" prop="repo_name" width="200" show-overflow-tooltip />
        <el-table-column label="分支" prop="branch" width="80" align="center" />
        <el-table-column label="提交信息" prop="commit_message" min-width="150" show-overflow-tooltip />
        <el-table-column label="有变更" width="80" align="center">
          <template slot-scope="{row}">
            <el-tag :type="row.has_changes ? 'success' : 'info'" size="mini">
              {{ row.has_changes ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="耗时" width="80" align="center">
          <template slot-scope="{row}">
            {{ row.duration ? row.duration + 's' : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="部署时间" prop="start_at" width="150" />
        <el-table-column label="仓库 URL" min-width="200">
          <template slot-scope="{row}">
            <el-link v-if="row.repo_url" :href="row.repo_url" target="_blank" type="primary">
              {{ row.repo_url }}
            </el-link>
            <span v-else style="color: #999;">-</span>
          </template>
        </el-table-column>
        <el-table-column label="错误信息" prop="error_message" width="200" show-overflow-tooltip />
      </el-table>
      <div slot="footer">
        <el-button @click="githubHistoryDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 部署历史详情对话框 -->
    <el-dialog
      title="Cloudflare 部署历史"
      :visible.sync="historyDialogVisible"
      width="900px"
    >
      <el-table :data="deploymentHistory" border>
        <el-table-column label="ID" prop="id" width="60" align="center" />
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="{row}">
            <el-tag :type="getDeployStatusType(row.status)">
              {{ getDeployStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="配置" prop="config_name" width="150" show-overflow-tooltip />
        <el-table-column label="文件/页面" width="100" align="center">
          <template slot-scope="{row}">
            {{ row.files_count }} / {{ row.pages_count }}
          </template>
        </el-table-column>
        <el-table-column label="耗时" width="80" align="center">
          <template slot-scope="{row}">
            {{ row.duration ? row.duration + 's' : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="部署时间" prop="start_at" width="150" />
        <el-table-column label="部署人" prop="user_name" width="100" />
        <el-table-column label="URL" min-width="200">
          <template slot-scope="{row}">
            <el-link v-if="row.deployment_url" :href="row.deployment_url" target="_blank" type="primary">
              {{ row.deployment_url }}
            </el-link>
            <span v-else style="color: #999;">-</span>
          </template>
        </el-table-column>
        <el-table-column label="错误信息" prop="error_message" width="200" show-overflow-tooltip />
      </el-table>
      <div slot="footer">
        <el-button @click="historyDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      :title="dialogStatus === 'create' ? '新建网站' : '编辑网站'"
      :visible.sync="dialogFormVisible"
      width="800px"
    >
      <el-form
        ref="dataForm"
        :model="temp"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="网站名称" prop="name">
          <el-input v-model="temp.name" placeholder="请输入网站名称" />
        </el-form-item>

        <el-form-item label="域名" prop="domain">
          <el-input v-model="temp.domain" placeholder="example.com" />
          <span style="font-size: 12px; color: #999;">域名用于网站访问和文件存储</span>
        </el-form-item>

        <el-form-item label="网站描述">
          <el-input
            v-model="temp.description"
            type="textarea"
            :rows="3"
            placeholder="简单描述网站用途..."
          />
        </el-form-item>

        <el-form-item label="前端框架" prop="framework">
          <el-select v-model="temp.framework" placeholder="选择前端框架">
            <el-option label="Bootstrap 5" value="bootstrap5" />
            <el-option label="Tailwind CSS" value="tailwind" />
            <el-option label="Bulma" value="bulma" />
            <el-option label="自定义" value="custom" />
          </el-select>
        </el-form-item>

        <el-form-item label="主色调">
          <el-color-picker v-model="temp.primary_color" />
          <span style="margin-left: 10px;">{{ temp.primary_color }}</span>
          <span style="margin-left: 10px; color: #999; font-size: 12px;">主要品牌色，用于按钮、链接等</span>
        </el-form-item>

        <el-form-item label="辅助色">
          <el-color-picker v-model="temp.secondary_color" />
          <span style="margin-left: 10px;">{{ temp.secondary_color }}</span>
          <span style="margin-left: 10px; color: #999; font-size: 12px;">次要颜色，用于背景、边框等</span>
        </el-form-item>

        <el-form-item label="强调色">
          <el-color-picker v-model="temp.accent_color" />
          <span style="margin-left: 10px;">{{ temp.accent_color }}</span>
          <span style="margin-left: 10px; color: #999; font-size: 12px;">强调色，用于高亮、提示等</span>
        </el-form-item>

        <el-form-item label="AI系统提示词">
          <el-input
            v-model="temp.ai_system_prompt"
            type="textarea"
            :rows="4"
            placeholder="描述网站定位、风格、受众等，帮助AI更好地生成内容..."
          />
        </el-form-item>

        <el-form-item label="品牌指南">
          <el-input
            v-model="temp.ai_brand_guidelines"
            type="textarea"
            :rows="3"
            placeholder="JSON格式: {&quot;tone&quot;: &quot;专业&quot;, &quot;style&quot;: &quot;简洁&quot;, &quot;keywords&quot;: [&quot;创新&quot;, &quot;可靠&quot;]}"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <!-- 生产环境同步对话框 -->
    <el-dialog
      title="同步生产环境网站"
      :visible.sync="syncDialogVisible"
      width="900px"
      :close-on-click-modal="false"
    >
      <div v-loading="loadingProductionWebsites">
        <el-alert
          type="info"
          :closable="false"
          style="margin-bottom: 20px;"
        >
          <div slot="title">
            <strong>从生产环境同步网站配置和页面</strong>
          </div>
          请选择要同步的网站。如果本地已存在相同域名的网站，可选择是否覆盖。
        </el-alert>

        <!-- 同步选项 -->
        <el-form label-width="120px" style="margin-bottom: 20px;">
          <el-form-item label="同步选项">
            <el-checkbox v-model="syncOptions.includePages">同步页面数据</el-checkbox>
            <el-checkbox v-model="syncOptions.overwrite" style="margin-left: 20px;">覆盖已存在的网站</el-checkbox>
          </el-form-item>
        </el-form>

        <!-- 网站列表 -->
        <el-table
          ref="productionWebsiteTable"
          :data="productionWebsites"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />

          <el-table-column label="网站名称" min-width="200">
            <template slot-scope="{row}">
              <div>
                <strong>{{ row.name }}</strong>
                <el-tag v-if="row.exists_locally" type="warning" size="mini" style="margin-left: 10px;">
                  本地已存在
                </el-tag>
              </div>
              <div style="font-size: 12px; color: #999;">{{ row.domain }}</div>
            </template>
          </el-table-column>

          <el-table-column label="框架" width="120" align="center">
            <template slot-scope="{row}">
              <el-tag size="small">{{ row.framework }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="页面数" width="100" align="center">
            <template slot-scope="{row}">
              <el-tag type="info" size="small">{{ row.page_count }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="描述" min-width="200" show-overflow-tooltip>
            <template slot-scope="{row}">
              {{ row.description || '-' }}
            </template>
          </el-table-column>

          <el-table-column label="创建时间" width="160">
            <template slot-scope="{row}">
              {{ row.created_at }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div slot="footer">
        <el-button @click="syncDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          icon="el-icon-refresh"
          :loading="syncing"
          :disabled="selectedWebsites.length === 0"
          @click="handleConfirmSync"
        >
          {{ syncing ? '同步中...' : `同步选中的 ${selectedWebsites.length} 个网站` }}
        </el-button>
      </div>
    </el-dialog>

    <!-- 删除网站对话框（含云端图片管理） -->
    <delete-website-dialog
      :visible.sync="deleteDialogVisible"
      :website-id="deleteWebsiteId"
      :website-name="deleteWebsiteName"
      :website-domain="deleteWebsiteDomain"
      @deleted="handleWebsiteDeleted"
    />
  </div>
</template>

<script>
import { Get, Post, Put } from '@/api/static_web/website'
import { TriggerBuild } from '@/api/static_web/build'
import { deployWebsite } from '@/api/static_web'
import { Get as GetCloudflareConfig, DeployToCloudflare, GetDeploymentHistory } from '@/api/static_web/cloudflare'
import { getGitHubConfigs, deployToGitHub, getGitHubDeploymentHistory, checkGitHubConflict } from '@/api/static_web_github'
import DeleteWebsiteDialog from './components/DeleteWebsiteDialog'
import request from '@/utils/request'

export default {
  name: 'StaticWebsite',
  components: {
    DeleteWebsiteDialog
  },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        pagesize: 20,
        kw: ''
      },
      temp: {
        id: undefined,
        name: '',
        domain: '',
        description: '',
        framework: 'bootstrap5',
        primary_color: '#007bff',
        secondary_color: '#6c757d',
        accent_color: '#ffc107',
        ai_system_prompt: '',
        ai_brand_guidelines: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        name: [{ required: true, message: '请输入网站名称', trigger: 'blur' }],
        domain: [{ required: true, message: '请输入域名', trigger: 'blur' }],
        framework: [{ required: true, message: '请选择前端框架', trigger: 'change' }]
      },
      // Cloudflare 部署相关
      cloudflareDialogVisible: false,
      cloudflareConfigs: [],
      selectedConfigId: null,
      deploymentHistory: [],
      currentWebsite: null,
      loadingConfigs: false,
      deploying: false,
      historyDialogVisible: false,
      configsLoaded: false, // 标记配置是否已加载
      loadingHistory: false, // 防止重复加载历史
      openingCloudflareDialog: false, // 防止重复点击
      // GitHub 部署相关
      githubDialogVisible: false,
      githubConfigs: [],
      selectedGithubConfigId: null,
      githubDeploymentHistory: [],
      loadingGithubConfigs: false,
      deployingToGithub: false,
      githubHistoryDialogVisible: false,
      githubCommitMessage: '',
      // 删除网站对话框
      deleteDialogVisible: false,
      deleteWebsiteId: null,
      deleteWebsiteName: '',
      deleteWebsiteDomain: '',
      // 生产环境同步
      canSyncFromProduction: false,
      syncDialogVisible: false,
      loadingProductionWebsites: false,
      productionWebsites: [],
      selectedWebsites: [],
      syncing: false,
      syncOptions: {
        includePages: true,
        overwrite: false
      }
    }
  },
  created() {
    this.getList()
    this.checkSyncAvailable()
  },
  methods: {
    getList() {
      this.listLoading = true
      const params = `page=${this.listQuery.page}&pagesize=${this.listQuery.pagesize}&kw=${this.listQuery.kw}`
      Get(null, params).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pagesize = val
      this.getList()
    },
    handlePageChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        domain: '',
        description: '',
        framework: 'bootstrap5',
        primary_color: '#007bff',
        secondary_color: '#6c757d',
        ai_system_prompt: '',
        ai_brand_guidelines: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          Post(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$message({
              message: '创建成功',
              type: 'success'
            })
            this.getList()
          })
        }
      })
    },
    handleEdit(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          Put(this.temp.id, this.temp).then(() => {
            this.dialogFormVisible = false
            this.$message({
              message: '更新成功',
              type: 'success'
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row) {
      // 使用新的删除对话框，支持云端图片管理
      this.deleteWebsiteId = row.id
      this.deleteWebsiteName = row.name
      this.deleteWebsiteDomain = row.domain
      this.deleteDialogVisible = true
    },
    handleWebsiteDeleted(result) {
      // 网站删除成功后刷新列表
      this.getList()
    },
    handleView(row) {
      this.$router.push(`/static_web/pages?website_id=${row.id}`)
    },
    handleManagePages(row) {
      this.$router.push(`/static_web/pages?website_id=${row.id}`)
    },
    handleConfig(row) {
      this.$router.push(`/website-config/${row.id}`)
    },
    handleBuild(row) {
      this.$confirm('确定构建该网站吗？将生成所有已发布的页面文件。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        TriggerBuild(row.id).then(response => {
          this.$message({
            message: '构建成功',
            type: 'success'
          })
          this.getList()
        })
      })
    },
    getFrameworkType(framework) {
      const types = {
        'bootstrap5': 'primary',
        'tailwind': 'success',
        'bulma': 'warning',
        'custom': 'info'
      }
      return types[framework] || 'info'
    },
    getBuildStatusType(status) {
      const types = {
        'success': 'success',
        'failed': 'danger',
        'pending': 'warning'
      }
      return types[status] || 'info'
    },
    getBuildStatusText(status) {
      const texts = {
        'success': '成功',
        'failed': '失败',
        'pending': '进行中'
      }
      return texts[status] || '未构建'
    },
    handleDeploy(row) {
      this.$confirm('确定部署该网站吗？将在static_sites目录创建网站文件。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '正在部署...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        deployWebsite(row.id).then(response => {
          loading.close()
          if (response.success) {
            this.$message({
              message: '部署成功！',
              type: 'success'
            })
            this.getList()
          } else {
            this.$message({
              message: response.error || '部署失败',
              type: 'error'
            })
          }
        }).catch(error => {
          loading.close()
          this.$message({
            message: '部署失败: ' + error.message,
            type: 'error'
          })
        })
      })
    },
    handlePreview(row) {
      // 打开新窗口预览网站
      const previewUrl = `${process.env.VUE_APP_BASE_API}/static_sites/${row.domain}/index.html`
      window.open(previewUrl, '_blank')
    },
    // 处理部署命令
    handleDeployCommand(command, row) {
      if (command === 'local') {
        this.handleDeploy(row)
      } else if (command === 'cloudflare') {
        this.handleCloudflareDialog(row)
      } else if (command === 'github') {
        this.handleGithubDialog(row)
      } else if (command === 'github-pull') {
        this.handleGithubPull(row)
      }
    },
    // 处理"更多"菜单命令
    handleMoreCommand(command, row) {
      if (command === 'preview') {
        this.handlePreview(row)
      } else if (command === 'config') {
        this.handleConfig(row)
      } else if (command === 'cloud-images') {
        this.handleCloudImages(row)
      } else if (command === 'edit') {
        this.handleEdit(row)
      } else if (command === 'delete') {
        this.handleDelete(row)
      }
    },
    handleCloudImages(row) {
      // 跳转到云端图片管理页面
      this.$router.push(`/static_web/cloud-images?website_id=${row.id}`)
    },
    // 打开 Cloudflare 部署对话框
    handleCloudflareDialog(row) {
      this.currentWebsite = row
      this.selectedConfigId = null
      this.cloudflareDialogVisible = true

      // 对话框打开后加载数据
      this.$nextTick(() => {
        this.loadCloudflareData()
      })
    },
    // 加载 Cloudflare 数据（配置和历史）
    loadCloudflareData() {
      // 加载配置列表
      this.loadingConfigs = true
      GetCloudflareConfig().then(response => {
        this.cloudflareConfigs = response.data || []
        this.loadingConfigs = false

        if (this.cloudflareConfigs.length === 0) {
          this.$message.warning('暂无 Cloudflare 配置，请先添加配置')
        }

        // 配置加载完成后，加载历史
        this.loadDeploymentHistory()
      }).catch(error => {
        this.loadingConfigs = false
        console.error('加载配置失败:', error)
        this.$message.error('加载 Cloudflare 配置失败')
      })
    },
    // 加载部署历史
    loadDeploymentHistory() {
      if (!this.currentWebsite) {
        return
      }

      GetDeploymentHistory(this.currentWebsite.id).then(response => {
        this.deploymentHistory = response.data || []
      }).catch(() => {
        this.deploymentHistory = []
      })
    },
    // 确认 Cloudflare 部署
    handleCloudflareDeployConfirm() {
      if (!this.selectedConfigId) {
        this.$message.warning('请选择 Cloudflare 配置')
        return
      }

      this.$confirm(
        `确定要将网站部署到 Cloudflare Pages 吗？\n\n每次部署都会创建一个新版本，请不要频繁部署。`,
        '确认部署',
        {
          confirmButtonText: '确定部署',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: false
        }
      ).then(() => {
        this.deploying = true

        DeployToCloudflare(this.currentWebsite.id, this.selectedConfigId).then(response => {
          this.deploying = false
          this.$message.success(response.msg || '部署成功！')
          // 刷新列表
          this.getList()
          // 重新加载部署历史
          this.loadDeploymentHistory()
          // 关闭对话框
          this.cloudflareDialogVisible = false
        }).catch(error => {
          this.deploying = false
          console.error('部署失败:', error)
          this.$message.error('部署失败')
        })
      }).catch(() => {
        // 用户取消
      })
    },
    // 查看完整部署历史
    viewFullHistory() {
      this.historyDialogVisible = true
    },
    // 跳转到 Cloudflare 配置页面
    goToCloudflareConfig() {
      this.$router.push('/static_web/cloudflare-cfg')
    },
    // 获取部署状态类型
    getDeployStatusType(status) {
      const types = {
        'success': 'success',
        'failed': 'danger',
        'pending': 'warning',
        'uploading': 'info'
      }
      return types[status] || 'info'
    },
    // 获取部署状态文本
    getDeployStatusText(status) {
      const texts = {
        'success': '成功',
        'failed': '失败',
        'pending': '准备中',
        'uploading': '上传中'
      }
      return texts[status] || '未知'
    },
    // ============ GitHub 部署相关方法 ============
    // 打开 GitHub 部署对话框
    handleGithubDialog(row) {
      this.currentWebsite = row
      this.selectedGithubConfigId = null
      this.githubCommitMessage = `Update ${row.name}`
      this.githubDialogVisible = true

      // 对话框打开后加载数据
      this.$nextTick(() => {
        this.loadGithubData()
      })
    },
    // 加载 GitHub 数据（配置和历史）
    loadGithubData() {
      // 加载配置列表
      this.loadingGithubConfigs = true
      getGitHubConfigs().then(response => {
        this.githubConfigs = response.data || []
        this.loadingGithubConfigs = false

        if (this.githubConfigs.length === 0) {
          this.$message.warning('暂无 GitHub 配置，请先添加配置')
        }

        // 配置加载完成后，加载历史
        this.loadGithubDeploymentHistory()
      }).catch(error => {
        this.loadingGithubConfigs = false
        console.error('加载 GitHub 配置失败:', error)
        this.$message.error('加载 GitHub 配置失败')
      })
    },
    // 加载 GitHub 部署历史
    loadGithubDeploymentHistory() {
      if (!this.currentWebsite) {
        return
      }

      getGitHubDeploymentHistory(this.currentWebsite.id).then(response => {
        this.githubDeploymentHistory = response.data || []
      }).catch(() => {
        this.githubDeploymentHistory = []
      })
    },
    // 确认 GitHub 部署
    handleGithubDeployConfirm() {
      if (!this.selectedGithubConfigId) {
        this.$message.warning('请选择 GitHub 配置')
        return
      }

      // 先检查是否有冲突
      const checkData = {
        config_id: this.selectedGithubConfigId,
        commit_message: this.githubCommitMessage || `Update ${this.currentWebsite.name}`
      }

      checkGitHubConflict(this.currentWebsite.id, checkData).then(checkResponse => {
        const conflictInfo = checkResponse.data

        if (conflictInfo.has_conflict) {
          // 有冲突，显示冲突对话框
          const info = conflictInfo.conflict_info
          this.$confirm(
            `检测到远程仓库有新的变更！\n\n` +
            `远程有 ${info.remote_commits || 0} 个新提交\n` +
            `本地有 ${info.local_commits || 0} 个提交\n\n` +
            `如果继续推送，远程的变更将被覆盖。是否强制推送？`,
            '检测到冲突',
            {
              confirmButtonText: '强制推送',
              cancelButtonText: '取消',
              type: 'warning',
              dangerouslyUseHTMLString: false
            }
          ).then(() => {
            // 用户选择强制推送
            this.executeGithubDeploy(true)
          }).catch(() => {
            // 用户取消
          })
        } else {
          // 无冲突，正常推送
          this.$confirm(
            `确定要将网站推送到 GitHub 吗？\n\n将会创建或更新 GitHub 仓库。`,
            '确认推送',
            {
              confirmButtonText: '确定推送',
              cancelButtonText: '取消',
              type: 'info',
              dangerouslyUseHTMLString: false
            }
          ).then(() => {
            this.executeGithubDeploy(false)
          }).catch(() => {
            // 用户取消
          })
        }
      }).catch(error => {
        console.error('检查冲突失败:', error)
        // 检查失败，询问用户是否继续
        this.$confirm(
          `无法检查远程仓库状态，是否继续推送？`,
          '提示',
          {
            confirmButtonText: '继续推送',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          this.executeGithubDeploy(false)
        }).catch(() => {
          // 用户取消
        })
      })
    },
    // 执行 GitHub 部署
    executeGithubDeploy(force = false) {
      this.deployingToGithub = true

      const data = {
        config_id: this.selectedGithubConfigId,
        commit_message: this.githubCommitMessage || `Update ${this.currentWebsite.name}`,
        force: force
      }

      deployToGitHub(this.currentWebsite.id, data).then(response => {
        this.deployingToGithub = false
        if (response.success) {
          this.$message.success(response.msg || '推送成功！')
          // 刷新列表
          this.getList()
          // 重新加载部署历史
          this.loadGithubDeploymentHistory()
          // 关闭对话框
          this.githubDialogVisible = false
        } else {
          this.$message.error(response.msg || '推送失败')
        }
      }).catch(error => {
        this.deployingToGithub = false
        console.error('推送失败:', error)

        // 检查是否是推送被拒绝错误
        const errorMsg = error.response?.data?.msg || error.message || '推送失败'
        if (errorMsg.includes('推送被拒绝') || errorMsg.includes('non-fast-forward')) {
          this.$confirm(
            `推送被拒绝：远程仓库有新的变更。\n\n是否强制推送覆盖远程变更？`,
            '推送失败',
            {
              confirmButtonText: '强制推送',
              cancelButtonText: '取消',
              type: 'error'
            }
          ).then(() => {
            // 用户选择强制推送，递归调用
            this.executeGithubDeploy(true)
          })
        } else {
          this.$message.error(errorMsg)
        }
      })
    },
    // 查看 GitHub 完整部署历史
    viewGithubFullHistory() {
      this.githubHistoryDialogVisible = true
    },
    // 跳转到 GitHub 配置页面
    goToGithubConfig() {
      this.$router.push('/static_web/github-cfg')
    },
    // 获取 GitHub 部署状态类型
    getGithubDeployStatusType(status) {
      const types = {
        'success': 'success',
        'failed': 'danger',
        'pending': 'warning',
        'creating_repo': 'info',
        'pushing': 'info'
      }
      return types[status] || 'info'
    },
    // 获取 GitHub 部署状态文本
    getGithubDeployStatusText(status) {
      const texts = {
        'success': '成功',
        'failed': '失败',
        'pending': '等待中',
        'creating_repo': '创建仓库',
        'pushing': '推送中'
      }
      return texts[status] || '未知'
    },
    // 检查是否可以同步生产环境
    async checkSyncAvailable() {
      try {
        const response = await request({
          url: '/static_web/api/sync/check/',
          method: 'get'
        })
        if (response.success) {
          this.canSyncFromProduction = response.data.can_sync
        }
      } catch (error) {
        console.error('检查同步功能失败:', error)
        this.canSyncFromProduction = false
      }
    },
    // 打开同步对话框
    async handleSyncFromProduction() {
      this.syncDialogVisible = true
      this.loadingProductionWebsites = true
      try {
        const response = await request({
          url: '/static_web/api/sync/list-production-websites/',
          method: 'get'
        })
        if (response.success) {
          this.productionWebsites = response.data
        } else {
          this.$message.error(response.msg || '获取生产环境网站列表失败')
        }
      } catch (error) {
        this.$message.error('获取生产环境网站列表失败: ' + (error.response?.data?.msg || error.message))
      } finally {
        this.loadingProductionWebsites = false
      }
    },
    // 处理表格选择变化
    handleSelectionChange(selection) {
      this.selectedWebsites = selection
    },
    // 确认同步
    async handleConfirmSync() {
      if (this.selectedWebsites.length === 0) {
        this.$message.warning('请至少选择一个网站进行同步')
        return
      }

      const websiteIds = this.selectedWebsites.map(w => w.id)
      const hasExistingWebsites = this.selectedWebsites.some(w => w.exists_locally)

      let confirmMessage = `确认同步 ${this.selectedWebsites.length} 个网站吗？`
      if (hasExistingWebsites && !this.syncOptions.overwrite) {
        confirmMessage += '\n\n注意：部分网站在本地已存在，将被跳过。'
      } else if (hasExistingWebsites && this.syncOptions.overwrite) {
        confirmMessage += '\n\n警告：部分网站在本地已存在，将被覆盖！'
      }
      if (this.syncOptions.includePages) {
        confirmMessage += '\n将同时同步页面数据。'
      }

      this.$confirm(confirmMessage, '确认同步', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        this.syncing = true
        try {
          const response = await request({
            url: '/static_web/api/sync/from-production/',
            method: 'post',
            data: {
              website_ids: websiteIds,
              include_pages: this.syncOptions.includePages,
              overwrite: this.syncOptions.overwrite
            }
          })
          if (response.success) {
            this.$message.success(response.msg)
            this.syncDialogVisible = false
            // 刷新网站列表
            this.getList()
          } else {
            this.$message.error(response.msg)
          }
        } catch (error) {
          this.$message.error('同步失败: ' + (error.response?.data?.msg || error.message))
        } finally {
          this.syncing = false
        }
      }).catch(() => {
        // 用户取消操作
      })
    }
  }
}
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}
.filter-item {
  margin-right: 10px;
}
</style>
